#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pylibmc
import settings

expire_time = settings.cache_expire_M

def client():
    _servers = list(settings.cache_servers)
    _mc = pylibmc.Client(_servers, binary=True)
    _mc.behaviors = {'tcp_nodelay': True, 'ketama': True}
    return _mc

def add(key, value, time=expire_time):
    global pool
    key = key.encode('utf-8') if isinstance(key, unicode) else key
    
    result = False
    with pool.reserve() as _mc:
        result = _mc.add(key, value, time)

    return result

def delete(key):
    global pool
    key = key.encode('utf-8') if isinstance(key, unicode) else key
    
    result = False
    with pool.reserve() as _mc:
        result = _mc.delete(key)

    return result

def set(key, value, time=expire_time):
    global pool 
    key = key.encode('utf-8') if isinstance(key, unicode) else key

    result = False
    with pool.reserve() as _mc:
        result = _mc.set(key, value, time)

    return result

def get(key):
    global pool
    key = key.encode('utf-8') if isinstance(key, unicode) else key

    result = None
    with pool.reserve() as _mc:
        result = _mc.get(key)

    return result

mc = client()
pool = pylibmc.ThreadMappedPool(mc)

